/**
 * @author 雷明浩
 * @date 2025/5/29 10:31
 */
public class RemoveNthFromEnd {
    // leetcode 删除链表的倒数第N个节点
    // https://leetcode.cn/problems/remove-nth-node-from-end-of-list/description/?envType=study-plan-v2&envId=top-100-liked
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode slow = head;
        ListNode fast = head;
        ListNode prev = null;
        for (int i = 0; i < n-1; i++) {
            fast = fast.next;
        }
        while (fast.next != null) {
            prev = slow;
            slow = slow.next;
            fast = fast.next;
        }
        if (slow == head) {
            head = head.next;
        }else {
            prev.next = slow.next;
        }
        return head;
    }
}